package com.sq.goodline.service;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.sq.goodline.controller.dto.AccessTokenDto;
import com.sq.goodline.dao.ParaCfgDao;
import com.sq.goodline.dao.po.ParaCfg;
import com.sq.goodline.util.HttpUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class AccessTokenService {

	
    public final String paraKey="AxbToken";
	@Autowired
	ParaCfgDao paraCfgDao;
	@Autowired
    private MailService mailService;
	/**
	 * axbToken2小时有效,优先从本地获取
	 * @throws Exception 
	 */
	public AccessTokenDto accessToken(){
		try {
			ParaCfg para = paraCfgDao.selectById(paraKey);
			if(para!=null) {
				Date d = para.getCreateTime();
				
				AccessTokenDto dto = JSON.parseObject(para.getParaValue(), AccessTokenDto.class);
				int expIn = dto.getResult().getExpire_in();//有效时间，通常是7200秒
				long exp = d.getTime()+expIn*1000-10*60*1000;//提前10分钟重新获取

				if(System.currentTimeMillis()<exp) {//有效期内
					return dto;
				}else {
					int a = paraCfgDao.deleteById(para.getParaKey());
					log.info("删除过期token：{}",a);
				}
			}
			
			String url = "http://223.255.252.183:30001/oauth/ue/auth/authenticate?appkey=05a2538d122cf16b296b600a27927d28&secret=d3a81b3420e5855a77b52598e75722e2";
			log.info("重新获取token,URL:{}",url);
			String result = HttpUtils.doGet(url);
			log.info("获取token响应报文：{}",result);
			
			if(StringUtils.isNotBlank(result)) {
				AccessTokenDto dto = JSON.parseObject(result, AccessTokenDto.class);
				if(dto.getCode()==0) {
					
					ParaCfg token = new ParaCfg();
					token.setParaKey(paraKey);
					token.setParaValue(result);
					int i = paraCfgDao.insert(token);
					log.info("axbToken保存完成：{}",i);
				}
				return dto;
			}
		}catch(Exception e) {
			log.error("获取axbtoken异常",e);
			mailService.sendSimpleMail("获取axbtoken异常", e.getMessage());
		}
		return null;
	}
}
